// pages/main/search.js
var toolutils = require("../../../../utils/tool-utils.js")
var httpUtils = require('../../../../utils/https-utils.js')
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data1: [],
    history: [],
  },
  bindCancel: function (e) {
    this.setData({
      inputTxt: ''
    })
  },
  bindDelete: function (e) {
    toolutils.setFormId(e.detail.formId)
    this.setData({
      history: []
    })
    wx.removeStorage({ key: 'search_history' })
  },
  bindSearch: function (e) {
    var value = e.detail.value;
    
    if (value == null || value == '') {
      wx.showToast({
        title: '输入不能为空！'
      })
      return
    }
    this.putSearch(value,1) 

  },
  bindItem: function (e) {
    toolutils.setFormId(e.detail.formId)
    var index = e.currentTarget.dataset.index
    var value = that.data.data1[index].hotword_val
    this.putSearch(value,2)
  },
  bindItem2: function (e) {
    toolutils.setFormId(e.detail.formId)
    var index = e.currentTarget.dataset.index
    var value = that.data.history[index]
    this.putSearch(value, 1)
  },
  putSearch: function (value,flag) {
    var that = this;
    var history = that.data.history;
    if (history == null) {
      history = []
      history.unshift(value)
    } else {
      for (var i = 0; i < history.length; i++) {
        if (history[i] === value) {
          history.splice(i, 1);
          break;
        }
      }
      history.unshift(value); // 再添加到第一个位置
    }
    toolutils.pageTo('/page/pack-index/pages/search-list/search-list?keyWord=' + value, 1)
    that.setData({
      history:history
    })
    wx.setStorage({
      key: "search_history",
      data: history,
      success: function (res) {

      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    getData()
    wx.getStorage({
      key: 'search_history',
      success: function (res) {
        console.log(res)
        if (res.errMsg == "getStorage:ok"){
          that.setData({
            history: res.data
          })
        }else{
        } 
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
//获取热门搜索词
function getData(){
  httpUtils.getHotwords({},function(res){
    that.setData({
      data1:res
    })
  },function(e){

  })

}